package com.liu.file.table;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 *	@author 刘忠奇
 *  创建时间 2012-12-13上午9:24:32
 *  
 */
public class SaveImgToPoco {
	public static String save(String filePath,String fileName) throws Exception{
		URL url=null;
		URLConnection conn=null;
		HttpURLConnection httpConn=null;
		BufferedReader read=null;
		StringBuffer sb = new StringBuffer();
		String cookie="";
		try {
			System.out.println("login poco...");
			url = new URL("http://my.poco.cn/module_common/login/poco_login_act.php");
			conn = url.openConnection();
			httpConn = (HttpURLConnection)conn;
			httpConn.setRequestMethod("POST");
			//httpConn.setRequestProperty("Cookie", sid);
			 httpConn.setRequestProperty("Content-Type",
		                "application/x-www-form-urlencoded");
			conn.setDoOutput(true);// 是否输入参数
			sb.append("locate="+URLEncoder.encode("http://my.poco.cn/manage/","GBK")+"&sbmit="+URLEncoder.encode("登录","GBK"));
			sb.append("&login_type=0&CookieDate=1&act=login&warm_tag=1&pass_word=cmaker&dont_remember_login_state=1&user_name="+URLEncoder.encode("273980392@qq.com","GBK"));
		    byte[] bypes = sb.toString().getBytes("GBK");
		    conn.getOutputStream().write(bypes);// 输入参数
		    sb.setLength(0);
			read = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
			String lineStr;
			while((lineStr = read.readLine())!=null){
				sb.append(lineStr);
			}
			cookie = "";
			String cookieVal = null;
			  String key=null;
			     for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++ ) {
			               if (key.equalsIgnoreCase("set-cookie")) {
			                cookieVal = conn.getHeaderField(i);
			                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
			                cookie=cookie+cookieVal+";";
			               }
			            }
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
				try {
					if(read!=null)
						read.close();
					if(httpConn!=null)
						httpConn.disconnect();
					System.out.println("upload image to poco...");
					url = new URL("http://imgup-s.poco.cn/ultra_upload_service/upload.mypoco_items.php");
					httpConn = (HttpURLConnection) url.openConnection();
					httpConn.setRequestMethod("POST");
					httpConn.setDoOutput(true);
					httpConn.setDoInput(true);
					httpConn.setUseCaches(false);
					String boundary="---------------------------114782935826962";
					String bLine = "\r\n--" + boundary + "\r\n";
					
					sb.setLength(0);
					sb.append("--"+boundary+"\r\n");
					sb.append("Content-Disposition: form-data; name=\"set_name\"\r\n\r\n");
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"opus\"; filename=\""+fileName+"\"\nContent-Type: image/"+fileName.split("\\.")[1]+"\r\n\r\n");
	 				byte[] head=sb.toString().getBytes();
					sb.setLength(0);
					FileInputStream fs = new FileInputStream(filePath+fileName);
					byte[]  buffer  =  new  byte[1444];  
					int byteread;
					int total=0;
		            while  (  (byteread  = fs.read(buffer))  !=  -1){total+=byteread;};
		        	   if(fs!=null)
		        		   fs.close();
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"water_type\"\r\n\r\npoco");
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"is_add_water\"\r\n\r\n1");
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"redirect_url\"\r\n\r\nhttp://my.poco.cn/album/album_items_edit_t_y.php?redirect_url=&op=edit&item_ids[]=%item_id%");
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"title\"\r\n\r\n");
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"item_type\"\r\n\r\nalbum");
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"tag_name\"\r\n\r\n");
					sb.append(bLine);
					sb.append("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
					sb.append(bLine);
					sb.append("--");
					 byte[] end =sb.toString().getBytes();
					httpConn.setRequestProperty("Host", "imgup-s.poco.cn");
					httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0");
					httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
					httpConn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
					httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
					httpConn.setRequestProperty("Connection", "http://my.poco.cn/album/album_uploader.php");
					httpConn.setRequestProperty("Cookie", cookie);
					httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
					httpConn.setRequestProperty("Content-Length", String.valueOf(head.length+total+end.length));
					
					DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
					out.write(head);
					fs = new FileInputStream(filePath+fileName);
					while  (  (byteread  =  fs.read(buffer))  !=  -1)  {  
		                   out.write(buffer,  0,  byteread);  
		               }  
					try{
						fs.close();
						out.write(end);
						out.flush();
						out.close();
						sb.setLength(0);
						String lineStr;
						read = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"GBK"));
						while((lineStr = read.readLine())!=null){
							sb.append(lineStr);
						}
						
						try {
							if(read!=null)
								read.close();
							if(httpConn!=null)
								httpConn.disconnect();
							String link = sb.toString();
							int n = link.indexOf("window.location");
							link = link.substring(n+19, link.indexOf("'",n+19));
							
							System.out.println("get uploaded image url...");
							url = new URL(link);
							httpConn = (HttpURLConnection) url.openConnection();
							httpConn.setRequestMethod("GET");
							httpConn.setRequestProperty("Cookie", cookie);
							httpConn.setUseCaches(false);
							httpConn.connect();
							read = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"GBK"));
							while((lineStr = read.readLine())!=null){
								sb.append(lineStr);
							}
							link = sb.toString();
							n = link.indexOf("item_thumbnail_img_0");
							link = link.substring(n+27,link.indexOf("\"",n+27));
							System.out.println("image url :"+link);
							link = link.substring(0,link.length()-8)+".jpg";
							try {
								if(read!=null)
									read.close();
								if(httpConn!=null)
									httpConn.disconnect();
								return link;
							} catch (IOException e) {
								e.printStackTrace();
								return null;
							}
					}catch(Exception e){
						e.printStackTrace();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
